package com.ljl.ningwei.controller;

import com.ljl.ningwei.domain.*;
import com.ljl.ningwei.dto.MaterialListByJoinDTO;
import com.ljl.ningwei.entity.Category;
import com.ljl.ningwei.entity.Material;
import com.ljl.ningwei.common.page.PageInfoByPC;
import com.ljl.ningwei.common.result.Result;
import com.ljl.ningwei.service.CategoryService;
import com.ljl.ningwei.service.MaterialService;
import com.ljl.ningwei.common.utils.ImagesUtils;
import com.ljl.ningwei.common.utils.TimeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 吕佳乐
 * 2025-03-13 20:39
 */
@RestController
@RequiredArgsConstructor
@Slf4j
@Validated
public class MaterialController {

    private final MaterialService materialService;
    private final CategoryService categoryService;

    /**
     * 获取物料
     * 分页查询
     *
     * @return
     */
    @RequestMapping("/material/list")
    public Result<PageVO<PageInfoByPC>> getlList(@RequestParam(name = "page") Integer page,
                                                 @RequestParam(name = "pageSize") Integer pageSize,
                                                 @RequestParam(name = "keyword", required = false) String keyword) {
        PageInfoByPC<Material> pageInfoByPC;
        Map<Long, String> categoryMap;
        try {
            pageInfoByPC = materialService.getMaterialListByPc(page, pageSize, keyword);
            String categoryIds = pageInfoByPC.getList().stream()
                    .filter(Objects::nonNull)  // 过滤掉 null
                    .map(Material::getCategoryId)
                    .distinct()
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));
            List<Category> categoryList = categoryService.listByIds(categoryIds);
            categoryMap = categoryList.stream().collect(Collectors.toMap(Category::getId, category -> category.getName()));
        } catch (Exception e) {
            // 或者使用日志框架记录详细信息
            e.printStackTrace();
            log.info("异常:{}" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        PageVO<PageInfoByPC> pageVO = new PageVO<>(pageInfoByPC);
        List<MaterialListVO> materialListVOList = pageInfoByPC.getList()
                .stream()
                .map(material -> {
                    // 判断物料可能没有关联到分类情况
                    String categoryName = categoryMap.get(material.getCategoryId());
                    categoryName = categoryName == null ? "" : categoryName;
                    return new MaterialListVO()
                            .setId(material.getId())
                            .setMaterialName(material.getName())
                            .setCategoryName(categoryName)
                            .setProductName(material.getProductName())
                            .setMaterialCount(material.getMaterialCount())
                            .setImageUrls(ImagesUtils.getUrl(material.getImageUrls()));
                })
                .collect(Collectors.toList());
        pageVO.setList(materialListVOList);
        return Result.success(pageVO);
    }

    /**
     * 获取物料
     * 分页查询
     *
     * @return
     */
    @RequestMapping("/material/listjoin")
    public Result<PageVO<PageInfoByPC>> listByJoin(@RequestParam(name = "page") Integer page,
                                                 @RequestParam(name = "pageSize") Integer pageSize,
                                                 @RequestParam(name = "keyword", required = false) String keyword) {
        PageInfoByPC<MaterialListByJoinDTO> pageInfoByPC;
        try {
            pageInfoByPC = materialService.getMaterialListByJoinDTO(page, pageSize, keyword);
        } catch (Exception e) {
            // 或者使用日志框架记录详细信息
            e.printStackTrace();
            log.info("异常:{}" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        PageVO<PageInfoByPC> pageVO = new PageVO<>(pageInfoByPC);
        List<MaterialListVO> materialListVOList = pageInfoByPC.getList()
                .stream()
                .map(entity -> {
                    // 判断物料可能没有关联到分类情况
                    return new MaterialListVO()
                            .setId(entity.getId())
                            .setMaterialName(entity.getMaterialName())
                            .setCategoryName(entity.getCategoryName())
                            .setProductName(entity.getProductName())
                            .setMaterialCount(entity.getMaterialCount())
                            .setImageUrls(ImagesUtils.getUrl(entity.getImageUrls()));
                })
                .collect(Collectors.toList());
        pageVO.setList(materialListVOList);
        return Result.success(pageVO);
    }

    @RequestMapping("/material/create")
    public Result<Void> create(@RequestParam("name") String name,
                               @RequestParam("categoryId") Long categoryId,
                               @RequestParam("productName") String productName,
                               @RequestParam("materialCount") Integer materialCount,
                               @RequestParam(value = "imageUrls") String imageUrls) {
        try {
            materialService.edit(null, name, categoryId, productName, materialCount, imageUrls);
        } catch (Exception e) {
            // 或者使用日志框架记录详细信息
            log.info("异常: " + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return Result.success();
    }

    @RequestMapping("/material/update")
    public Result<MaterialUpdateVO> update(@RequestParam("id") Long id,
                                           @RequestParam(value = "name", required = false) String name,
                                           @RequestParam(value = "categoryId", required = false) Long categoryId,
                                           @RequestParam(value = "productName", required = false) String productName,
                                           @RequestParam(value = "materialCount", required = false) Integer materialCount,
                                           @RequestParam(value = "imageUrls", required = false) String imageUrls) {
        try {
            // 更新成功
            materialService.edit(id, name, categoryId, productName, materialCount, imageUrls);
        } catch (Exception e) {
            e.printStackTrace();
            // 或者使用日志框架记录详细信息
            log.info("异常:{} " + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return Result.success();
    }

    @RequestMapping("/material/delete")
    public Result<MaterialDeleteVO> delete(@RequestParam("id") Long id) {
        try {
            // 物料删除
            materialService.delete(id);
        } catch (Exception e) {
            // 捕获异常并记录日志
            log.info("异常:{}" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return Result.success();
    }

    /**
     * 物料详情信息
     * 跟随id
     *
     * @param id
     * @return
     */
    @RequestMapping("/material/info")
    public Result<MaterialInfoVO> getInfo(@RequestParam(name = "id") Long id) {
        Material material = null;
        Category category = null;
        try {
            material = materialService.getById(id);
            category = categoryService.getById(material.getCategoryId());
        } catch (Exception e) {
            log.info("异常为:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        MaterialInfoVO materialInfoVO = new MaterialInfoVO()
                .setMaterialName(material.getName())
                .setCategoryName(category.getName())
                .setProductName(material.getProductName())
                .setMaterialCount(material.getMaterialCount())
                .setImageUrls(ImagesUtils.getUrl(material.getImageUrls()))
                .setCreateTime(TimeUtil.formatTime(material.getCreateTime()))
                .setUpdateTime(TimeUtil.formatTime(material.getUpdateTime()));
        return Result.success(materialInfoVO);
    }

}
